package com.example.chasshelper.dao;

import com.example.chasshelper.model.Classroom;
import com.example.chasshelper.model.Registration;
import com.example.chasshelper.model.Student;
import com.example.chasshelper.model.Teacher;
import com.example.chasshelper.utils.OkHttpUtils;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class RegistrationDao {
    private OkHttpClient okHttpClient = OkHttpUtils.getClient();
    private String ipUrl = OkHttpUtils.getUrl();
    private String url;

    /*
     * 根据学生id和课堂id查询签到记录
     * */
    public Registration findByStudentIdAndClassroomId(Student student, Classroom classroom) {
        url = ipUrl + "/registration/findByStudentIdAndClassroomId?studentId=" + student.getStudentId() + "&classroomId=" + classroom.getClassroomId();
        System.out.println("url:"+url);
        Registration registration=new Registration();
        Request request = new Request.Builder().url(url).get().build();
        try {
            //执行同步get请求
            Response response = okHttpClient.newCall(request).execute();
            //获得返回的字符串
            String string =response.body().string();
            //开始解析服务器传过来的json数据
            Gson gson = new Gson();
            //接收数据
            registration = gson.fromJson(string, Registration.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return registration;
    }
    /*
     * 学生签到
     * */
    public  void signIn(Registration registration) {
        url = ipUrl + "/registration/update?registrationId=" + registration.getRegistrationId() + "&registrationState=已签到";
        System.out.println("url:"+url);
        Request request = new Request.Builder().url(url).get().build();
        final Map<String, Object> resultMap = new HashMap<>();
        //执行异步get请求
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println("成功");
            }
        });
    }

}
